/*
 * @Author: hongbin
 * @Date: 2022-12-22 18:13:13
 * @LastEditors: hongbin
 * @LastEditTime: 2022-12-25 11:06:13
 * @Description:话题
 */
import Link from "next/link";
import { CSSProperties, FC, useCallback, useEffect, useMemo, useRef, useState } from "react";
import styled, { css, DefaultTheme, ThemedCssFunction } from "styled-components";
import { get, post } from "../src/api";
import SEOHeader from "../src/components/SEO";
import { ITopic } from "../src/components/Topic/List";
import { useAuth } from "../src/context/AuthProvide";
import { UserNameSlice } from "../src/helper";
import { showMessage } from "../src/HUI/MessageBar";
import { fadeIn, flexCenter, FlexDiv } from "../src/styled";
import { mongoIDToDate, mongoIDToDateTime } from "../src/utils";

interface IProps {
    data: ITopic;
}
/**
 * 服务端反悔的评论数据
 */
interface ITopicComment {
    _id: string;
    senderId: string;
    senderName: string;
    topicId: string;
    content: string;
    reply?: string;
    allow: boolean;
}

const Topic: FC<IProps> = ({ data }) => {
    const { user } = useAuth();
    const isSelf = useMemo(() => user._id == data.userId, [data.userId, user._id]);
    const inputRef = useRef<HTMLTextAreaElement>(null);
    const [havInput, setHavInput] = useState(false);
    const [loading, setLoading] = useState(false);
    const [comments, setComments] = useState<ITopicComment[]>([]);

    useEffect(() => {
        get<{ data: ITopicComment[] }>("/Comment/queryByTopic?id=" + data._id).then((r) => {
            console.log(r);
            if (r.data) {
                setComments(r.data.reverse());
            }
        });
    }, [data._id]);

    const inputListener = useCallback((e: Event) => {
        //@ts-ignore
        const val = e.target.value;
        setHavInput(val);
    }, []);

    useEffect(() => {
        if (inputRef.current) {
            inputRef.current.addEventListener("input", inputListener);
            return () => {
                inputRef.current && inputRef.current.removeEventListener("input", inputListener);
            };
        }
    }, [inputListener, inputRef]);

    const sendTopic = useCallback(async () => {
        setLoading(true);
        const body = {
            senderId: user._id,
            senderName: user.name,
            topicId: data._id,
            content: inputRef.current!.value,
            //回复其他评论，评论的id
            reply: undefined,
        };
        const { data: res } = await post<{ data: ITopicComment }>("/Topic/comment", body);
        console.log(res);
        if (res._id) {
            showMessage("评论成功", 600);
            setComments((p) => [res, ...p]);
            inputRef.current!.value = "";
        }
        setLoading(false);
    }, [data._id, user._id, user.name]);

    return (
        <Container>
            <SEOHeader title={data.title} />
            <TopicDesc topic={data} />
            <Talk>
                <textarea ref={inputRef} placeholder="我来说两句"></textarea>
                {havInput ? (
                    <button onClick={loading ? undefined : sendTopic}>{loading ? "发送中.." : "发送"}</button>
                ) : null}
            </Talk>
            {comments.map((c) => (
                <Comment style={{ background: c.allow ? undefined : "#760808" }} key={c._id}>
                    <Link href={`/homepage?id=${c.senderId}`}>
                        <UserName isSelf={c.senderId == user._id}>{UserNameSlice(c.senderName)}</UserName>
                    </Link>
                    <FlexDiv column>
                        <Date>{mongoIDToDateTime(c._id)}</Date>
                        <Content>{c.allow ? c.content : "违规评论"}</Content>
                    </FlexDiv>
                </Comment>
            ))}
        </Container>
    );
};

export default Topic;

/**
 * 服务端执行 获取用户配置
 */
export const getServerSideProps = async ({ query: { id } }: any) => {
    const { data } = await get("/Topic/detail?id=" + id);
    // console.log("hi", data);

    const props = {} as { data: ITopic };

    if (data) props.data = data;

    return {
        props,
    };
};

export const TopicDesc = ({
    topic,
    style,
    onClick,
}: {
    topic: ITopic;
    style?: CSSProperties;
    onClick?: VoidFunction;
}) => {
    const { user } = useAuth();
    return (
        <FlexDiv onClick={onClick} style={style}>
            <Link href={`/homepage?id=${topic.userId}`}>
                <UserName isSelf={user._id == topic.userId}>{UserNameSlice(topic.userName)}</UserName>
            </Link>
            <FlexDiv column>
                <Date>{mongoIDToDateTime(topic._id)}</Date>
                <Title>{topic.title}</Title>
                <Content>{topic.content}</Content>
            </FlexDiv>
        </FlexDiv>
    );
};

const Date = styled.span`
    font-size: 1vw;
`;

const Comment = styled.div`
    background: #178d02;
    padding: 0.5vh;
    margin: 0.5vh 0.5vw;
    border-radius: 0.5vw;
    display: flex;
`;

const Talk = styled.div`
    position: relative;

    button {
        position: absolute;
        bottom: 1.5vh;
        left: calc(60% - 5.5vw);
        width: 5vw;
        border-radius: 0.3vw;
        background: #116702;
        border: 3px solid #178d02;
        color: #eee;
        cursor: pointer;
        padding: 0.4vh;
        animation: ${fadeIn} 0.5s;
    }

    textarea {
        color: #eee;
        width: 60%;
        resize: none;
        height: 10vh;
        border-radius: 1vw;
        background: #167705;
        border: 3px solid transparent;
        padding: 0.3vh 0.5vw;
        margin: 0.5vh 0;
        outline: none;
        transition: 0.3s;
        :focus {
            border: 3px solid #1e890b;
        }
        ::-webkit-input-placeholder {
            color: #0b4401;
        }
    }
`;

const UserName = styled.span<{ isSelf: boolean }>`
    ${flexCenter};
    color: #fff;
    font-size: 3vw;
    width: 4vw;
    text-align: center;
    height: 4vw;
    border-radius: 4vw;
    background: #167705;
    margin-right: 2vw;
    position: relative;
    ${({ isSelf }) =>
        isSelf &&
        css`
            ::after {
                content: "自己";
                position: absolute;
                bottom: 0;
                right: -15px;
                background: #0c3803;
                font-size: max(12px, min(15px, 1vw));
                border-radius: 3px;
                padding: 0 3px;
            }
        `}
`;
const Title = styled.span`
    color: #fff;
    font-size: 2vw;
`;
const Content = styled.span`
    color: #eee;
    font-size: 1.5vw;
`;

const Container = styled.div`
    display: flex;
    flex-direction: column;
    width: 80vw;
    background: #249e0e;
    margin: 3vh auto;
    padding: 1vh 1vw;
    border-radius: 1vw;
`;
